/*
 *  $Id$

    Copyright (C) 2008  Nathaniel Waisbrot

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package termint.brains;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import termint.util.Pair;

/**
 * @author Nathaniel Waisbrot
 * in charge of turning messages from shopkeepers into a price list
 * converts to the (possible) base price, but doesn't do the identification work
 * Prices might be off be a bit due to integer rounding
 */
public class PriceWatcher implements MessageListener {
	public static interface Listener {
		public void price(String name, Pair<Integer,Integer> prices);
	}

	private final StatsWatcher stats;
	private final List<Listener> listeners = new ArrayList<>();
	
	public PriceWatcher(StatsWatcher stats) {
		this.stats = stats;
	}
	
	public void addListener(Listener l) {
		listeners.add(l);
	}

	private static final Pattern pickup_price = Pattern.compile("\"For you, (?:scum |(?:good|honored|most gracious|esteemed|most renowned and sacred) (?:creature|lady|sir)); only (\\d+) (?:per|for this) (.+)[.]\"");
	private static final Pattern offer_price = Pattern.compile("offers (\\d+) gold pieces for your (.+).  Sell");
	@Override
	public void newText(String text) {
		Matcher m = pickup_price.matcher(text);
		if (m.find()) {
			double price = Integer.parseInt(m.group(1));
			String name = m.group(2);
			
			int cha = stats.cha();
			if (cha > 18)
				price *= 2;
			else if (cha > 17)
				price *= 1.5;
			else if (cha > 15)
				price *= (4./3.);
			else if (cha < 6)
				price /= 2.;
			else if (cha < 8)
				price /= 1.5;
			else if (cha < 11)
				price /= (4./3.);
			
			double price2 = price / (4./3.);
			
			notifyListeners(name, new Pair<Integer,Integer>((int) Math.round(price2), (int) Math.round(price)));
			return;
		}
	}

	private void notifyListeners(String name, Pair<Integer,Integer> is) {
		for (Listener l : listeners)
			l.price(name, is);
	}

	@Override public void clear() {}

	@Override
	public void newQuestion(String text) {
		Matcher m = offer_price.matcher(text);
		if (m.find()) {
			double price = Integer.parseInt(m.group(1));
			String name = m.group(2);
			double price2 = price * (8./3.);
			price *= 2;
			notifyListeners(name, new Pair<Integer,Integer>((int) Math.round(price), (int) Math.round(price2)));
			return;
		}
	}
}
